/*
 * @Author: i@rysa.cn
 * @Date: 2022-08-01 17:18:01
 * @LastEditTime: 2022-09-20 11:10:48
 * @LastEditors: i@rysa.cn
 * @Description:
 * @FilePath: /go-utils/wechat/mini/qrcode/qrcode.go
 */
package qrcode

import (
	"encoding/json"
	"errors"
	"fmt"

	"gitee.com/rysa/go-utils/request"
	accesstoken "gitee.com/rysa/go-utils/wechat/mini/access_token"
	"gitee.com/rysa/go-utils/wechat/mini/config"
	"gitee.com/rysa/go-utils/wechat/mini/params"
)

type qrcode struct {
	*config.MiniConfig
}

func NewQrcode(cfg *config.MiniConfig) *qrcode {
	return &qrcode{cfg}
}

const (
	getwxacodeunlimit = "https://api.weixin.qq.com/wxa/getwxacodeunlimit"
	getwxacode        = "https://api.weixin.qq.com/wxa/getwxacode"
)

/**
 * @name: 获取不限制的小程序码
 * @description:
 * @return {*}
 */
func (q *qrcode) GetUnlimitedQRCode(data params.QrcodeParams) ([]byte, error) {
	token, err := accesstoken.NewAccessToken(q.MiniConfig).GetAccessToken()
	if err != nil {
		return nil, err
	}
	url := fmt.Sprintf(getwxacodeunlimit+"?access_token=%s", token)
	req := request.NewRequest()
	req.SetBody(data)
	// req.SetOutput(path.Join("public/", "1.png"))
	res, err := req.Post(url)
	if err != nil {
		return nil, err
	}
	var result params.QrcodeResponse
	json.Unmarshal(res.Body(), &result)
	if result.Errcode == 0 {
		return res.Body(), nil
	}
	return nil, errors.New(result.Errmsg)
}

/**
 * @name: 获取小程序码
 * @description: 适用于需要的码数量较少的业务场景。通过该接口生成的小程序码，永久有效，有数量限制
 * @param {params.QrcodeParams} data
 * @return {*}
 */
func (q *qrcode) GetQrcode(data params.QrcodeParams) ([]byte, error) {
	token, err := accesstoken.NewAccessToken(q.MiniConfig).GetAccessToken()
	if err != nil {
		return nil, err
	}
	url := fmt.Sprintf(getwxacode+"?access_token=%s", token)
	req := request.NewRequest()
	req.SetBody(data)
	res, err := req.Post(url)
	if err != nil {
		return nil, err
	}
	var result params.QrcodeResponse
	json.Unmarshal(res.Body(), &result)
	if result.Errcode != 0 {
		return nil, errors.New(result.Errmsg)
	}
	return res.Body(), nil
}
